import type { Module } from "vuex";
import type { Tabs } from "@model/views";
import type { RootState, TabsState } from "@model/store";

const setting: Module<TabsState, RootState> = {
	namespaced: true,
	state: {
		keepList: [
			{
				name: "Dashboard",
				path: "/dashboard",
				keepAlive: true,
			},
		],
		activeList: [],
	},
	getters: {
		keepList: state => state.keepList,
		activeList: state => state.activeList,
	},
	mutations: {
		INIT_TABS(state) {
			state.keepList = [
				{
					name: "Dashboard",
					path: "/dashboard",
					keepAlive: true,
				},
			];
			state.activeList = [];
		},
		ADD_TABS(state, value: Tabs) {
			const tab = [...state.keepList, ...state.activeList].find(
				item => item.path === value.path,
			);
			!tab && value.path !== "/login" && state.activeList.push(value);
		},
		REMOVE_TABS(state, index: number) {
			state.activeList.splice(index, 1);
		},
		REMOVE_ALL_TABS(state) {
			state.activeList = [];
		},
		REMOVE_OTHER_TABS(state, index: number) {
			state.activeList = [state.activeList[index]];
		},
		KEEP_TABS(state, value: Tabs) {
			state.keepList.push(value);
		},
		REMOVE_KEEP_TABS(state, index: number) {
			state.keepList.splice(index, 1);
		},
		REMOVE_LEFT_TABS(state, index: number) {
			state.activeList.splice(0, index);
		},
		REMOVE_RIGHT_TABS(state, index: number) {
			state.activeList.splice(index + 1, state.activeList.length);
		},
	},
	actions: {
		// 初始化 tabs
		INIT_TABS({ commit }) {
			commit("INIT_TABS");
		},
		// 添加 tabs
		ADD_TABS({ commit }, value: Tabs) {
			commit("ADD_TABS", value);
		},
		// 移除 tabs
		REMOVE_TABS({ commit }, index: number) {
			commit("REMOVE_TABS", index);
		},
		// 移除所有 tabs
		REMOVE_ALL_TABS({ commit }) {
			commit("REMOVE_ALL_TABS");
		},
		// 移除其他 tabs
		REMOVE_OTHER_TABS({ commit }, index: number) {
			commit("REMOVE_OTHER_TABS", index);
		},
		// 移除左边tabs
		REMOVE_LEFT_TABS({ commit }, index: number) {
			commit("REMOVE_LEFT_TABS", index);
		},
		// 移除右边tabs
		REMOVE_RIGHT_TABS({ commit }, index: number) {
			commit("REMOVE_RIGHT_TABS", index);
		},

		// 保持固定
		KEEP_TABS({ commit, state }, index: number) {
			commit("KEEP_TABS", state.activeList[index]);
			commit("REMOVE_TABS", index);
		},
		// 移除固定
		REMOVE_KEEP_TABS({ commit, state }, index: number) {
			const tab = state.keepList[index];
			commit("REMOVE_KEEP_TABS", index);
			commit("ADD_TABS", tab);
		},
	},
};

export default setting;
